import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  TextInput,
  Text,
  Image,
  Modal,
  ScrollView,
  TouchableOpacity
} from 'react-native'

import NavBar from '../../../../components/PublicHeader';
import fetchWebApi from '../../../../public/WebApi/fetchBase';
import getStorageValue from '../../../../utils/getStorageValue';
import Layer from "../../../../utils/Layer";

import {
  Constant
} from '../../../../public/js/constant';
import {
  deviceWidth,
  deviceHeight,
} from '../../../../utils/Global';
import {
  GET_EDITSKILLTAG_LIST,
  GET_SECONDARYLABEL_LIST,
  UPDATE_APPLABEL_LIST,
  POST_APPLABELCUSTOM,
  POST_ABELSEARCHCUSTOM,
  POST_LABELDELCUSTOM
} from '../../../../public/WebApi/myInfoDataInterface/userInfoListApi';

export default class editSkillTag extends Component {
  constructor(props) {
    super(props)
    const {
      editSkillTag
    } = this.props.navigation.state.params
    this.state = {
      topTitle: "编辑技能标签",
      titleColor: "#333",
      rightText: "完成",
      shanchu: require('../../../../assets/images/maillist/shanchu.png'),
      deleteMark: require('../../../../assets/images/socialcircle/delete_mark.png'),
      frameps: require('../../../../assets/images/search/Frameps.png'),
      ellipsess: require('../../../../assets/images/search/Ellipsess.png'),
      editSkillTag: editSkillTag, // 原本的技能标签
      customIconD: false,
      customIconBox: false,
      customIconBoxL: [],
      customIconBoxD: [],
      lID: [],
      title: "",
      customIconT: false,
      defaultTrue: false,
      defaultD: false,
      customDelet: false, // 自定义标签删除
      multipleChoice: false,// 自定义多选删除
      multipleCStyle: false,
      customD: [],//自定义删除id
      actionId: '', //点击选中的 id 
      labelID: "", // 获取第一个一级标签id 初始化
      primaryLabelList: [],// 一级标签列表
      secondaryLabelList: [], // 二级标签列表
      TagId: [],
      newArr: []
    };
  }

  componentDidMount = () => {
    // 获取一级标签列表
    this.primaryLabelFn()

    // 获取已选中 标签 初始化
    this.labelSearchcustom()

    // 初始化二级标签列表
    this.secondaryLabelWFN()

  }

  // 获取已选中 状态 初始化
  async labelSearchcustom() {
    const res = await fetchWebApi(POST_ABELSEARCHCUSTOM,
      {
        token: await getStorageValue(Constant.TOKEN)
      }, 'POST');
    if (res.status === 200) {
      this.setState({
        customIconBoxD: [],
        customIconBoxL: []
      })
      //  已选中标签逻辑判断
      this.labelSearchcustomFN(res)
    } else {
      // 弹窗提示
      Layer.showMsg("已选中标签获取失败");
      return
    }
  }

  // 已选中标签逻辑判断
  labelSearchcustomFN(res) {
    const {
      data
    } = res
    data.custom.map((item) => {
      if (item.flag) {
        this.state.customIconBoxD.push(item)
        this.state.TagId.push(item.id)
      } else {
        this.state.customIconBoxL.push(item)
      }
    })
    data.default.map((item1) => {
      this.state.customIconBoxD.push(item1)
      this.state.TagId.push(item1.id)
    })
    this.setState({
      defaultD: true
    })
  }

  // 获取一级标签列表
  async primaryLabelFn() {
    const res = await fetchWebApi(GET_EDITSKILLTAG_LIST,
      {
        token: await getStorageValue(Constant.TOKEN)
      }, 'GET');
    if (res.status === 200) {
      this.setState({
        primaryLabelList: res.data,
        labelID: res.data[0].id
      })
    } else {
      // 弹窗提示
      Layer.showMsg("一级标题获取失败");
      return
    }
  }

  // 初始化二级标签
  secondaryLabelWFN() {
    setTimeout(() => {
      const {
        labelID
      } = this.state
      if (labelID) {
        this.secondaryLabelFn(
          id = labelID
        )
      }
    }, 1000)
  }

  // 获取二级标签列表
  async secondaryLabelFn(id) {
    this.setState({
      actionId: id
    })
    const res = await fetchWebApi(GET_SECONDARYLABEL_LIST,
      {
        token: await getStorageValue(Constant.TOKEN),
        id: id
      }, 'POST');
    if (res.status === 200) {
      this.setState({
        secondaryLabelList: res.data.children
      })
    } else {
      // 弹窗提示
      Layer.showMsg("二级标签获取失败");
      return
    }
  }

  // 技能标签 编辑保存方法
  async editSkillTagGoBack() {
    const {
      TagId
    } = this.state
    const res = await fetchWebApi(UPDATE_APPLABEL_LIST,
      {
        token: await getStorageValue(Constant.TOKEN),
        id: TagId
      }, 'POST')
    if (res.status == 200) {
      const {
        navigation
      } = this.props
      navigation.state.params.refresh()
      navigation.goBack()// 返回上一级
    }
  }

  // 标签限制 为3个 处理
  processingEvents(item) {
    this.setState({
      customDelet: false,
      multipleChoice: false
    })
    if (!item.flag) {
      // 标签限制 逻辑判断
      this.processingEventsFN(item)
    } else {
      // 清除当前点击 取消的
      const { TagId } = this.state
      TagId.splice(TagId.findIndex(i =>
        i === item.id), 1)
      this.setState({
        flag: (item.flag = !item.flag)
      })
    }
  }

  // 标签限制 逻辑判断
  processingEventsFN(item) {
    const {
      TagId,
      customD,
      multipleChoice
    } = this.state
    if (TagId.length >= 3) {
      Layer.showMsg("最多添加数量3个");
      return
    } else {
      if (multipleChoice) {
        // 清除当前点击 取消的
        customD.splice(customD.findIndex(i =>
          i === item.id), 1)
        this.setState({
          f: (item.f = !item.f)
        })
      }
      this.setState({
        flag: (item.flag = !item.flag)
      })
      if (item.flag) {
        this.state.TagId.push(item.id)
      }
    }
  }

  // 技能搜索
  onChangeText = (inputText) => {
    this.setState({
      editSkillTag: inputText
    })
  }

  // 自定义标签
  onChangeCustom(title) {
    this.setState({
      title: title
    })
  }

  // 自定义标签
  async applabelCustom() {
    const {
      title
    } = this.state
    if (title) {
      if (title.length > 6) {
        return
      }
      this.setState({
        customIconT: false
      })
      const res = await fetchWebApi(POST_APPLABELCUSTOM,
        {
          token: await getStorageValue(Constant.TOKEN),
          title: title
        }, 'POST');
      // 自定义标签逻辑判断
      this.applabelCustomFN(res)
    } else {
      this.setState({
        customIconT: true
      })
      return
    }
  }

  // 自定义标签逻辑判断
  applabelCustomFN(res) {
    if (res.status === 200) {
      const data = res.data
      const {
        customIconBoxL
      } = this.state
      // customIconBoxL.splice(customIconBoxL.findIndex(i =>
      //   i.name === res.data.name
      // ), 1)
      // i === res.data.name), 1)

      this.state.customIconBoxL.push(data)
      this.setState({
        customIconD: false,
        title: "",
        defaultTrue: true
      })
    } else {
      // 弹窗提示
      Layer.showMsg("新增失败");
      return
    }
  }

  // 自定义标签删除方法
  customDelet(ID) {
    const {
      customIconBoxD
    } = this.state
    this.setState({
      lID: []
    })
    customIconBoxD.map((item) => {
      if (item.id == ID) {
        this.state.lID.push(item.id)
      }
    })
    const {
      lID
    } = this.state
    if (lID[0] === ID) {
      Layer.showMsg("当前标签已选中不可删除")
      return
    } else {
      // 自定义标签删除逻辑判断
      this.customDeletFN(ID)
    }
  }

  // 自定义标签多选删除
  multipleChoice(ID, item) {
    const {
      multipleCStyle,
      customIconBoxD
    } = this.state
    this.setState({
      multipleCStyle: !multipleCStyle
    })
    this.setState({
      f: item.f = !item.f
    })
    this.setState({
      lID: []
    })
    customIconBoxD.map((item) => {
      if (item.id == ID) {
        this.state.lID.push(item.id)
      }
    })
    // 自定义标签多选删除逻辑判断
    this.multipleChoiceFN(ID, item)
  }

  // 自定义标签多选删除逻辑判断
  multipleChoiceFN(ID, item) {
    const {
      lID
    } = this.state
    if (lID[0] === ID) {
      Layer.showMsg("已选中标签不可删除")
      this.setState({
        f: item.f = false
      })
      this.setState({
        multipleCStyle: false
      })
      return
    } else {
      this.state.customD.push(ID)
    }
  }
  // 自定义标签多选删除按钮
  multipleChoiceBTN() {
    this.customDeletFN()
  }

  // 自定义标签删除逻辑判断
  async customDeletFN(ID) {
    const {
      customD
    } = this.state
    if (ID) {
      this.state.customD.push(ID)
    }
    if (customD.length > 0) {
      const res = await fetchWebApi(POST_LABELDELCUSTOM,
        {
          token: await getStorageValue(Constant.TOKEN),
          id: customD
        }, 'POST');
      if (res.status === 200) {
        // 弹窗提示
        Layer.showMsg("删除成功");
        // 删除后重新刷新数据
        this.labelSearchcustom()
      } else {
        Layer.showMsg("删除失败");
        return
      }
    } else {
      Layer.showMsg("您还未选择删除项")
      return
    }
  }

  // 技能标签搜索 
  SkillTagInput = () => {
    return (
      < View >
        <TextInput
          onChangeText={inputText =>
            this.onChangeText(inputText)}
          inlineImagePadding={20}
          inlineImageLeft='search_icon'
          placeholder='搜索职业名称'
          style={styles.skillTagInput} />
      </View >
    )
  }

  // 一级标签列表
  PrimaryLabelBox = () => {
    const {
      primaryLabelList,
      actionId
    } = this.state
    return (
      <View style={styles.primaryLabel}>
        <ScrollView style={styles.scrollViewBox}>
          {primaryLabelList.map((item) => (
            <TouchableOpacity key={item.id}
              onPress={() => {
                // 获取二级标签 通过id查找
                this.secondaryLabelFn(item.id)
              }}>
              {/* 标题 一级区 */}
              <View style={styles.labelTitleBox} >
                {/* 判断选中的状态 */}
                <Text style={actionId === item.id ?
                  styles.labelTitleAction :
                  styles.labelTitleActionNo}>
                  {item.name}
                </Text>
              </View>
            </TouchableOpacity>
          ))}
        </ScrollView>
        {/* 自定义技能标签 展示弹窗按钮 */}
        {this.customIconB()}
      </View>
    )
  }
  // // 二级标签列表
  SecondaryLabelBox = () => {
    const {
      actionId,
      secondaryLabelList
    } = this.state
    return (
      <ScrollView style={styles.scrollViewBox}>
        {actionId !== 0 ?
          secondaryLabelList == null ? null :
            secondaryLabelList.map((itemTile) => (
              <View style={styles.secondaryLabel}
                key={itemTile.id}>
                <View style={styles.childLabelTitle}>
                  <Text style={styles.childLabelText}>
                    {itemTile.name}
                  </Text>
                </View>
                <View style={styles.content}>
                  {
                    itemTile.children == null ? null :
                      itemTile.children.map((item3, index) => {
                        this.state.newArr.push(item3)
                        return (
                          <TouchableOpacity key={index}
                            onPress={() => {
                              // 处理标签个数 为3个
                              this.processingEvents(item3)

                            }} style={styles.childLabelBox}>
                            <View style={item3.flag ?
                              styles.childLabel2 : styles.childLabel} >
                              <Text style={item3.flag ?
                                styles.labelText2 : styles.labelText}>
                                {item3.name}
                              </Text>
                            </View>
                          </TouchableOpacity>
                        )
                      })
                  }
                </View>
              </View>
            ))
          :
          this.customIconBox()}
      </ScrollView>
    )
  }
  // 自定义技能标签
  customIcon() {

    return (
      <TouchableOpacity
        style={styles.customIconBox}
        onPress={() => {
          this.setState({
            customIconD: true,
            actionId: 0,
            customDelet: false,
            multipleChoice: false
          })
        }}>
        <View style={styles.childLabel} >
          <Text style={styles.labelText}>
            新增
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
  // 自定义技能标签
  customIconB() {
    const {
      actionId
    } = this.state
    return (
      <TouchableOpacity
        style={styles.customIconBtnBox}
        onPress={() => {
          this.setState({
            customIconBox: true,
            actionId: 0,
            customDelet: false,
            multipleChoice: false
          })
        }}>
        <View style={styles.customIconBtn}>
          <Text style={actionId === 0 ?
            styles.labelTitleAction :
            styles.labelTitleActionNo}>其他</Text>
        </View>
      </TouchableOpacity>
    )
  }
  // 自定输入框文本提示
  promptText() {
    const {
      customIconT,
      title
    } = this.state
    if (title.length > 6) {
      return (
        <Text style={{
          color: "red"
        }}>标签字符不能超出6位</Text>
      )
    } else if (customIconT) {
      return (
        <Text style={{
          color: "red"
        }}>内容不能为空</Text>
      )
    }
  }
  // 自定义技能标签 弹窗
  customIconD() {
    const {
      customIconD,
      shanchu
    } = this.state
    return (
      <Modal
        animationType='fade'
        transparent={true}
        visible={customIconD}>
        <View style={styles.customIconWar}>
          <View style={styles.customIconModalBox}>
            <View style={styles.customIconWarModal}>
              <TouchableOpacity
                onPress={() => {
                  this.setState({
                    customIconD: false,
                    title: "",
                    customIconT: false
                  })
                }}>
                <Image style={{
                  width: 45,
                  height: 45
                }}
                  source={shanchu} />
              </TouchableOpacity>
            </View>
            <View style={styles.IsModalInputBox}>
              <Text style={styles.numberofText}>自定义技能标签</Text>
              <TextInput
                placeholder='请输入自定义技能标签'
                style={styles.IsModalInput}
                onChangeText={inputText =>
                  this.onChangeCustom(inputText)}
              />
              {/* 自定义提示 */}
              {this.promptText()}
              <TouchableOpacity onPress={() => {
                this.applabelCustom()
              }}>
                <View style={styles.IsModalBtnBox}>
                  <Text style={styles.IsModalBtn}>确定</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    )
  }

  // 自定义技能标签展示 弹窗
  customIconBox() {
    const {
      customIconBoxL,
      customIconBoxD,
      multipleChoice,
      customDelet,
      deleteMark,
      ellipsess,
      frameps
    } = this.state
    return (
      <View style={styles.customModalBox}>
        {
          customIconBoxD.length > 0 ?
            <Text>已选中标签</Text> : null
        }
        <View style={styles.content}>
          {
            customIconBoxD.length > 0 ?
              customIconBoxD.map((item3, index) => {
                this.state.newArr.push(item3)
                return (
                  <TouchableOpacity key={index}
                    onPress={() => {
                      // 处理标签个数 为3个
                      this.processingEvents(item3)

                    }} style={styles.childLabelBox}>
                    <View style={item3.flag ?
                      styles.childLabel2 : styles.childLabel} >
                      <Text style={item3.flag ?
                        styles.labelText2 : styles.labelText}>
                        {item3.name}
                      </Text>
                    </View>
                  </TouchableOpacity>
                )
              }) : null
          }
        </View>
        <View style={styles.titleTop}>
          <Text>新增自定义</Text>
          <View style={styles.multipleChoiceB}>
            <TouchableOpacity style={styles.customE}
              onPress={() => {
                this.setState({
                  multipleChoice: !multipleChoice,
                  customDelet: false
                })
              }}>
              <Text>多选</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.customE}
              onPress={() => {
                this.multipleChoiceBTN()
              }}>
              <Text>确定</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.customE}
              onPress={() => {
                this.setState({
                  customDelet: !customDelet,
                  multipleChoice: false
                })
              }}>
              <Text>编辑</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={styles.content}>
          {
            customIconBoxL.map((item3, index) => {
              this.state.newArr.push(item3)
              return (
                <TouchableOpacity key={index}
                  onPress={() => {
                    // 处理标签个数 为3个
                    this.processingEvents(item3)

                  }}>
                  <View style={item3.flag ?
                    styles.childLabel2 : styles.childLabel} >
                    <Text style={item3.flag ?
                      styles.labelText2 : styles.labelText}>
                      {item3.name}
                    </Text>
                    {/* 删除按钮 标签 */}
                    <View style={styles.customMarkBox}>
                      <TouchableOpacity onPress={() => {
                        this.customDelet(item3.id)
                      }}>
                        {customDelet ?
                          <View style={styles.iconBtn}>
                            <Image style={styles.customDelet}
                              source={deleteMark} />
                          </View>
                          : null}
                      </TouchableOpacity>
                      {multipleChoice ?
                        <TouchableOpacity
                          onPress={() => {
                            this.multipleChoice(item3.id, item3)
                          }}>
                          {
                            item3.f ?
                              <View style={styles.iconBtn}>
                                <Image style={{
                                  width: 15,
                                  height: 15
                                }}
                                  source={frameps} />
                              </View> :
                              <View style={styles.iconBtn}>
                                <Image
                                  source={ellipsess}
                                  style={{
                                    width: 15,
                                    height: 15
                                  }} />
                              </View>
                          }
                        </TouchableOpacity>
                        : null}
                    </View>
                  </View>
                </TouchableOpacity>
              )
            })
          }
          {/* 自定义技能标签 */}
          {this.customIcon()}
        </View>
      </View>
    )
  }
  render() {
    const {
      topTitle,
      titleColor,
      rightText
    } = this.state
    return (
      <View style={styles.editSkillTagWarper}>
        {/* 导航栏 */}
        <NavBar
          navigation={this.props.navigation}
          title={topTitle}
          titleColor={titleColor}
          right={rightText}
          pressRight={() => {
            this.editSkillTagGoBack() // 完成 保存
          }}
        />
        <View style={styles.editSkillTag}>
          {/* 技能标签搜索    */}
          {this.SkillTagInput()}
          <View style={styles.editSkillTagBox}>

            {/* 自定义技能标签 弹窗 */}
            {this.customIconD()}

            {/* 一级标签列表 */}
            {this.PrimaryLabelBox()}

            {/* 二级标签列表 */}
            {this.SecondaryLabelBox()}
          </View>
        </View>
      </View >
    )
  }
}
const styles = StyleSheet.create({
  editSkillTagWarper: {
    flex: 1,
    backgroundColor: "#fff",
  },
  editSkillTag: {
    height: deviceHeight,
    width: deviceWidth,
    paddingLeft: 16,
    paddingRight: 16,
  },
  customBtnBox: {
    marginTop: 20,
    flexDirection: "row",
    justifyContent: "space-around",
  },
  editSkillTagBox: {
    height: deviceHeight - 140,
    position: "relative",
    paddingTop: 15,
    flexDirection: "row",
    justifyContent: "space-between"
  },
  skillTagInput: {
    width: "100%",
    height: 40,
    backgroundColor: "rgba(196, 196, 196, 0.25)",
    borderWidth: 0,
    paddingLeft: 15,
    borderRadius: 5
  },
  scrollViewBox: {
    paddingTop: 10,
    paddingBottom: 60,
  },
  primaryLabel: {
    position: "relative",
    borderRightWidth: 1,
    borderRightColor: "rgba(0, 0, 0, 0.08)",
    width: 110,
  },
  labelTitleBox: {
    marginTop: 10,
    marginBottom: 10
  },
  labelTitleActionNo: {
    color: "#333",
    fontSize: 14
  },
  labelTitleAction: {
    color: "#1890FF",
    fontSize: 14
  },
  titleTop: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  multipleChoiceB: {
    flexDirection: "row"
  },
  customE: {
    justifyContent: "center",
    alignItems: "center",
    width: 50,
    height: 30,
  },
  content: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-start',
    flexWrap: 'wrap',
    marginBottom: 10,
  },
  defaultText: {
    color: "#333",
    fontSize: 14,
  },
  childLabelBox: {
    flexDirection: "row",
    flexWrap: "wrap",
  },
  customDelet: {
    width: 15,
    height: 15,
  },
  warperMultiple: {
    position: "absolute",
    bottom: 100
  },
  multipleBox: {
    paddingLeft: "3%",
    paddingRight: "3%",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#1890FF",
    borderRadius: 6,
  },
  customMarkBox: {
    position: "absolute",
    top: -18,
    right: -15,
    zIndex: 22
  },
  iconBtn: {
    width: 40,
    height: 40,
    justifyContent: "center",
    alignItems: "center",
  },
  multipleChoiceBox: {
    width: 15,
    height: 16,
    borderWidth: 1,
    borderRadius: 50,
    borderColor: "#999"
  },
  multipleChoiceBoxA: {
    width: 15,
    height: 16,
    borderWidth: 1,
    borderRadius: 50,
    borderColor: "#999",
    backgroundColor: "#1890FF"
  },
  childLabelText: {
    color: "#000",
    fontSize: 16,
  },
  secondaryLabel: {
    paddingBottom: 15,
    paddingLeft: 15,
  },
  childLabelTitle: {
    marginBottom: 10
  },
  childLabel: {
    position: "relative",
    width: deviceWidth / 3.7,
    paddingTop: deviceWidth / 60,
    paddingBottom: deviceWidth / 60,
    paddingLeft: deviceWidth / 70,
    paddingRight: deviceWidth / 70,
    marginTop: 15,
    marginRight: deviceWidth / 100,
    marginBottom: 5,
    borderRadius: 4,
    justifyContent: "center",
    alignItems: 'center',
    backgroundColor: "#E1F0FF"
  },
  childLabel2: {
    position: "relative",
    width: deviceWidth / 3.7,
    paddingTop: deviceWidth / 60,
    paddingBottom: deviceWidth / 60,
    paddingLeft: deviceWidth / 70,
    paddingRight: deviceWidth / 70,
    marginTop: 15,
    marginRight: deviceWidth / 100,
    marginBottom: 5,
    borderRadius: 4,
    justifyContent: "center",
    alignItems: 'center',
    backgroundColor: "#D7ECFF"
  },
  labelText: {
    fontSize: 13,
    color: "#616161"
  },
  labelText2: {
    fontSize: 13,
    color: "#0084FF"
  },
  customIconBox: {
    justifyContent: "center",
    alignItems: "center",
  },
  customIconBtnBox: {
    height: 40,
    justifyContent: "center",
  },
  customIconBtn: {
  },
  text: {
    color: "#fff",
    fontSize: 15
  },
  customIconWar: {
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(0,0,0,0.4)",
    justifyContent: "center",
    alignItems: "center"
  },
  customModalBox: {
    paddingLeft: 15,
  },
  customIconModalBox: {
    width: 300,
    backgroundColor: "#fff",
    borderRadius: 6,
    paddingLeft: 17,
    paddingRight: 17,
    paddingTop: 7,
    paddingBottom: 30
  },
  customIconWarModal: {
    flexDirection: "row-reverse"
  },
  numberofText: {
    textAlign: "center",
    fontSize: 20
  },
  IsModalInput: {
    width: "100%",
    height: 40,
    borderRadius: 6,
    fontSize: 14,
    paddingLeft: 15,
    backgroundColor: "#E9E9E9",
    marginTop: 20,
    marginBottom: 10
  },

  IsModalBtnBox: {
    width: "100%",
    height: 40,
    backgroundColor: "#1890FF",
    borderRadius: 6,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 10
  },
  IsModalBtn: {
    color: "#fff",
    fontSize: 18,
  },
})